// pages/square/square.js
Page({
  data: {
    keyWord: '',
    timer: null,
    scrollHeight:500,
    loading: false,  // 加载状态
    noMore: false,   // 是否无更多数据
    lastDoc: null,    // 最后一条文档（用于分页）
    app:null,
    db:null,
    userInfo:{},
    isLoggedIn:false,
    allData: [], // 所有数据

    // 下拉刷新相关
    refreshHeight: 80, // 刷新区域高度
    refreshTranslate: -80, // 刷新区域位移
    refreshStatus: 'pulling', // pulling, ready, loading
    startY: 0,
    currentY: 0,
    isRefreshing: false
  },
  onShow(){

  },
  onLoad() {
    wx.getSystemInfo({
      success: (res) => {
        console.log('getSystemInfo res',res)
        this.setData({
          scrollHeight: res.windowHeight - 50 // 减去导航栏高度
        });
      }
    });
    const app = getApp();
    this.setData({
      app:app
    })
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db
    })
    const userInfo = wx.getStorageSync('userInfo');
    console.log('business userInfo',userInfo)
    this.setData({
      isLoggedIn: !!userInfo,
      userInfo: userInfo || {},
      keyWord: '',
      timer: null,
      loading: false,  // 加载状态
      noMore: false,   // 是否无更多数据
      lastDoc: null,    // 最后一条文档（用于分页）
      allData: [], // 所有数据
    });
    this.loadOrderList(true);
  },

  // 模拟加载数据
  loadOrderList(init = false) {

    console.log('this.data.loading',this.data.loading,this.data.noMore,this.data.allData.length,this.data.keyWord)
    if (this.data.loading || this.data.noMore) return
    let data = {
      isPublic:true
    }
    if(this.data.keyWord.trim() !== ''){
      data.name = new RegExp(this.data.keyWord.trim(), 'i')
    }
    this.setData({ loading: true })
    wx.showLoading({ title: '加载中...' })
    this.data.db.collection('message')
    .where(data)
    .orderBy('createTime','desc')
    .skip(init ? 0 : this.data.allData.length) // 跳过已加载数据
    .limit(20) // 每次20条
    .get()
    .then(res => {
      if(res && res.data && res.data.length > 0){
        console.log('res',res.data)
        this.setData({
          allData: init ? res.data : [...this.data.allData, ...res.data],
          noMore: res.data.length < 20,
          lastDoc: res.data[res.data.length - 1], // 记录最后一条
        })
      }
    })
    .catch (err =>  {
      wx.showToast({ title: '加载失败', icon: 'none' })
    })
    .finally(() => {
      this.setData({ loading: false})
      wx.hideLoading()

      if(this.data.isRefreshing){
        this.resetRefresh()
        this.setData({ isRefreshing: false })
      }
    }) 
  },
  // 跳转到详情页
  navigateToDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/show/index?id=${id}`
    });
  },
  // 滚动到底部触发
  onReachBottom() {
    console.log('onReachBottom')
    this.loadOrderList()
  },
  onInput(e) {
    console.log('e',e)
    const value = e.detail.value.trim();
    this.setData({ keyWord: value });
    
    clearTimeout(this.data.timer);
    
    this.setData({
      timer : setTimeout(() => {
        this.setData({ 
          noMore: false,
          lastDoc:null,
          allData:[],
         })
        this.loadOrderList();
      }, 400)
    });
  },
     // 触摸开始
     onTouchStart(e) {
      console.log('onTouchStart e',e,this.data.isRefreshing)
     if (this.data.isRefreshing) return
     
     this.setData({
       startY: e.touches[0].clientY,
       currentY: e.touches[0].clientY
     })
   },
 
   // 触摸移动
   onTouchMove(e) {
     console.log('onTouchMove e',e,this.data.isRefreshing)
     if (this.data.isRefreshing) return
     
     const currentY = e.touches[0].clientY
     const deltaY = currentY - this.data.startY
     const scrollTop = this.getScrollTop()
 
     console.log('onTouchMove scrollTop',scrollTop,currentY,deltaY)
 
     // 只有在顶部且下拉时才触发
     if (scrollTop <= 0 && deltaY > 0) {
       const translateY = Math.min(deltaY * 0.5, this.data.refreshHeight)
       
       this.setData({
         currentY: currentY,
         refreshTranslate: translateY - this.data.refreshHeight,
         refreshStatus: translateY >= this.data.refreshHeight ? 'ready' : 'pulling'
       })
 
       // 阻止默认滚动
       if (deltaY > 0) {
         return false
       }
     }
   },
 
   // 触摸结束
   onTouchEnd() {
     console.log('onTouchEnd e',this.data.isRefreshing,this.data.refreshStatus)
     if (this.data.isRefreshing) return
 
     if (this.data.refreshStatus === 'ready') {
       // 开始刷新
       this.startRefresh()
     } else {
       // 恢复原位
       this.resetRefresh()
     }
   },
 
   // 开始刷新
   startRefresh() {
     this.setData({
       refreshStatus: 'loading',
       refreshTranslate: 0,
       isRefreshing: true,
       noMore: false,
       lastDoc:null,
     })
     this.loadOrderList(true);
   },
 
   // 重置刷新状态
   resetRefresh() {
     this.setData({
       refreshTranslate: -this.data.refreshHeight,
       refreshStatus: 'pulling'
     })
   },
   onScroll(){
 
   },
   // 获取滚动位置
   getScrollTop() {
     let scrop = 0;
       const query = this.createSelectorQuery()
       query.select('.order-list').scrollOffset()
       query.exec((res) => {
         console.log('getScrollTop res',res[0].scrollTop)
         // resolve(res[0] ? res[0].scrollTop : 0)
         scrop = res[0].scrollTop
       })
       return scrop
   },
});